package org.codehaus.activemq.service.impl;

import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import javax.jms.JMSException;
import org.codehaus.activemq.service.Dispatcher;
import org.codehaus.activemq.service.MessageContainer;
import org.codehaus.activemq.service.MessageContainerManager;

public abstract class MessageContainerManagerSupport
  implements MessageContainerManager
{
  protected Dispatcher dispatcher;
  protected Map messageContainers = new ConcurrentHashMap();

  public MessageContainerManagerSupport(Dispatcher dispatcher) {
    this.dispatcher = dispatcher;
    dispatcher.register(this);
  }

  public void start()
    throws JMSException
  {
    this.dispatcher.start();
  }

  public void stop()
    throws JMSException
  {
    this.dispatcher.stop();
    JMSException firstException = null;
    try {
      this.dispatcher.stop();
    }
    catch (JMSException e) {
      firstException = e;
    }

    for (Iterator iter = this.messageContainers.values().iterator(); iter.hasNext(); ) {
      MessageContainer container = (MessageContainer)iter.next();
      try {
        container.stop();
      }
      catch (JMSException e) {
        if (firstException == null) {
          firstException = e;
        }
      }
    }
    if (firstException != null)
      throw firstException;
  }
}